import {Button, Drawer, FormInstance, message, Popconfirm, Image} from 'antd';
import React, {useRef, useState} from 'react';
import {FooterToolbar, PageContainer} from '@ant-design/pro-layout';
import type {ActionType, ProColumns} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormDependency,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect,
} from '@ant-design/pro-form';
import ProDescriptions, {ProDescriptionsItemProps} from '@ant-design/pro-descriptions';
import {getRisk, loadCheckRisk, removeRisk, checkRisk, rejectRisk} from './service';
import type {RiskListItem, RiskListPagination} from './data';
import {loadOrgSelect} from '@/pages/Enterprise/Org/service';
import {loadPostSelect} from '@/pages/Enterprise/Post/service';
import {loadEmployeeSelect} from '@/pages/Employee/List/service';
import CheckModule from "@/components/CheckModule";

/**
 * 新增或更新风险信息
 *
 * @param fields
 */

const handleAdd = async (fields: RiskListItem) => {
  const hide = message.loading('正在审核');
  try {
    await checkRisk({...fields});
    hide();
    message.success('审核成功');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
/**
 * 新增或更新风险信息
 *
 * @param fields
 */
const handleReject = async (fields: RiskListItem) => {
  const hide = message.loading('正在拒绝');
  try {
    await rejectRisk({...fields});
    hide();
    message.success('成功拒绝');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
/**
 * 删除风险
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: RiskListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRisk(selectedRows.map((row) => row.riskId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const sourceTypeData = {
  1: {
    text: '人的不安全行为',
  },
  2: {
    text: '物的不安全状态',
  },
  3: {
    text: '不良环境',
  },
  4: {
    text: '管理缺陷',
  },
};
const possibleResultData = {
  人员伤亡: '人员伤亡',
  环境污染: '环境污染',
  社会影响: '社会影响',
  经济损失: '经济损失',
};
const riskTypeData = {
  物体打击: '物体打击',
  车辆伤害: '车辆伤害',
  机械伤害: '机械伤害',
  起重伤害: '起重伤害',
  触电: '触电',
  淹溺: '淹溺',
  灼烫: '灼烫',
  火灾: '火灾',
  高处坠落: '高处坠落',
  坍塌: '坍塌',
  冒顶片帮: '冒顶片帮',
  透水: '透水',
  放炮: '放炮',
  火药爆炸: '火药爆炸',
  瓦斯爆炸: '瓦斯爆炸',
  锅炉爆炸: '锅炉爆炸',
  容器爆炸: '容器爆炸',
  其他爆炸: '其他爆炸',
  中毒和窒息: '中毒和窒息',
  其他伤害: '其他伤害',
};
const riskLevelData = {
  1: {
    text: '较小',
    color: '#0000FF',
  },
  2: {
    text: '一般',
    color: '#E1E13A',
  },
  3: {
    text: '较大',
    color: '#FFA500',
  },
  4: {
    text: '重大',
    color: '#FF0000',
  },
};
const hierarchyData = {
  1: {
    text: '公司级',
    color: '#FF0000',
  },
  2: {
    text: '部门级',
    color: '#FFA500',
  },
  3: {
    text: '班组级',
    color: '#E1E13A',
  },
  4: {
    text: '岗位级',
    color: '#0000FF',
  },
};
const frequencyData = {
  1: {
    text: '每日一次',
  },
  2: {
    text: '每周一次',
  },
  3: {
    text: '每月一次',
  },
  4: {
    text: '每季度一次',
  },
  5: {
    text: '每年一次',
  },
  6: {
    text: '每半年一次',
  },
};
const requestOrg = async () => {
  return loadOrgSelect({status: '0'}).then(({data}) => {
    return data;
  });
};
const requestPost = async () => {
  return loadPostSelect().then(({data}) => {
    return data;
  });
};

const requestEmployee = async (param: any) => {
  return loadEmployeeSelect(param).then(({data}) => {
    return data;
  });
};

const RiskCheckPage: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<RiskListItem>();
  const [selectedRowsState, setSelectedRows] = useState<RiskListItem[]>([]);
  const columns: ProColumns<RiskListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '作业位置场所',
      dataIndex: 'place',
    },
    {
      title: '上报图片',
      dataIndex: 'upload',
      hideInSearch: true,
      hideInTable: true,
      render: (_, record) => <Image width={200} src={record.upload.image}
      />,
    },
    {
      title: '风险源',
      dataIndex: 'source',
      render: (_, record) => <span style={{whiteSpace: 'pre-wrap'}}>{record?.source}</span>,
    },
    {
      title: '风险等级',
      dataIndex: 'riskLevel',
      valueEnum: riskLevelData,
    },
    {
      title: '管控措施',
      dataIndex: 'measure',
      render: (_, record) => <span style={{whiteSpace: 'pre-wrap'}}>{record?.measure}</span>,
    },
    {
      title: '管控层级',
      dataIndex: 'hierarchy',
      hideInSearch: true,
      valueEnum: hierarchyData,
    },
    {
      title: '辨识频率',
      dataIndex: 'frequency',
      hideInSearch: true,
      valueEnum: frequencyData,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: false,
      initialValue: '0',
      valueEnum: {
        '-1': {
          text: '审核通过',
          status: 'Success',
        },
        '0': {
          text: '待审核',
          status: 'Default',
        },
        '-2': {
          text: '审核失败',
          status: 'Error',
        },
      },
    },
    {
      title: '来源',
      dataIndex: 'createMode',
      hideInForm: false,
      hideInSearch: true,
      initialValue: '2',
      valueEnum: {
        0: {
          text: '创建',
        },
        1: {
          text: '转化',
        },
        2: {
          text: '上报',
        },
        9: {
          text: '导入',
        },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
      defaultSortOrder: 'descend',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,

      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          查看
        </a>,
        <a
          key="edit"
          onClick={() => {
            formRef.current?.resetFields();
            setCurrentRow(record);
            setCheckMode(true);
            handleModalVisible(true);
          }}
        >
          审核
        </a>,
      ],
    },
  ];
  const [checkMode, setCheckMode] = useState<boolean>(true);
  let riskColor = {'4': '#FF0000', '3': '#FFA500', '2': '#E1E13A', '1': '#0000FF'};
  let hierarchyColor = {'1': '#FF0000', '2': '#FFA500', '3': '#E1E13A', '4': '#0000FF'};

  return (
    <CheckModule code={'SC'}>
      <PageContainer waterMarkProps={{content: ''}}>
        <ProTable<RiskListItem, RiskListPagination>
          headerTitle="风险列表"
          actionRef={actionRef}
          rowKey="riskId"
          search={{
            labelWidth: 120,
          }}
          request={loadCheckRisk}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
          params={{createMode: '2'}}
        />
        {selectedRowsState?.length > 0 && (
          <FooterToolbar
            extra={
              <div>
                已选择{' '}
                <a
                  style={{
                    fontWeight: 600,
                  }}
                >
                  {selectedRowsState.length}
                </a>{' '}
                个风险
              </div>
            }
          >
            <Popconfirm
              key="delete"
              title={`确认删除选中的${selectedRowsState.length}个风险?`}
              okButtonProps={{danger: true}}
              onConfirm={async () => {
                await handleRemove(selectedRowsState);
                setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="删除"
              cancelText="取消"
            >
              <Button danger>批量删除</Button>
            </Popconfirm>
            {/*<Button type="primary">批量审批</Button>*/}
          </FooterToolbar>
        )}
        <ModalForm<RiskListItem>
          title={'审核风险'}
          // width="600px"
          modalProps={{destroyOnClose: true, maskClosable: false}}
          layout={'horizontal'}
          labelCol={{span: 5}}
          wrapperCol={{pull: 1, offset: 1, span: 17}}
          formRef={formRef}
          // size={"large"}
          visible={createModalVisible}
          submitter={{
            submitButtonProps: {
              style: {
                display: 'none',
              },
            },
            render: (props, defaultDoms) => {
              return [
                ...defaultDoms,
                <Button
                  danger
                  key="reject"
                  onClick={async () => {
                    // @ts-ignore
                    const success = await handleReject(formRef.current?.getFieldsFormatValue?.());
                    if (success) {
                      setCurrentRow(undefined);
                      handleModalVisible(false);
                      if (actionRef.current) {
                        actionRef.current.reload();
                      }
                    }
                  }}
                >
                  拒绝
                </Button>,
                <Button
                  type="primary"
                  key="check"
                  onClick={() => {
                    props.submit();
                  }}
                >
                  通过
                </Button>,
              ];
            },
          }}
          onValuesChange={(f, v) => {
            if (f.hasOwnProperty('orgId') || f.hasOwnProperty('postId')) {
              formRef.current?.setFieldsValue({employeeId: undefined});
            }
          }}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentRow(undefined);
            }
            handleModalVisible(visible);
          }}
          onFinish={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          request={(params) => {
            if (params.riskId > 0) {
              return getRisk(params).then(({data}) => {
                return data;
              });
            } else {
              return new Promise<RiskListItem>((resolve) => {
                resolve({riskId: 0});
              });
            }
          }}
          params={{...currentRow}}
        >
          <ProFormText hidden name="riskId"/>
          {/* <ProFormSelect
          rules={[{ required: true }]}
          label={'审核结果'}
          name="status"
          fieldProps={{
            onChange: (value) => {
              if (value == '-1') {
                setCheckMode(true);
              } else if (value == '-2') {
                setCheckMode(false);
              }
            },
          }}
          valueEnum={{
            '-1': {
              text: '通过',
              status: 'Success',
            },
            '-2': {
              text: '拒绝',
              status: 'Error',
            },
          }}
        /> */}
          <ProFormSelect
            name="postId"
            label={'责任岗位'}
            rules={[{required: checkMode}]}
            request={requestPost}
            fieldProps={{
              placeholder: '请选择责任岗位',
              dropdownMatchSelectWidth: false,
            }}
          />
          <ProFormTreeSelect
            name="orgId"
            label={'责任部门'}
            request={requestOrg}
            tooltip={'责任部门可以限定到部门对应的的岗位'}
            fieldProps={{
              allowClear: true,
              placeholder: '请选择部门',
              treeDefaultExpandAll: true,
              treeLine: true,
              fieldNames: {label: 'label', value: 'id', children: 'children'},
            }}
          />

          <ProFormDependency name={['postId', 'orgId']}>
            {({postId, orgId}) => {
              if (postId || orgId) {
                return (
                  <ProFormSelect
                    name="employeeId"
                    label={'责任人'}
                    tooltip={'可以将风险限定到对应的人员'}
                    request={requestEmployee}
                    params={{postId, orgId}}
                    fieldProps={{
                      placeholder: '请选择责任岗位',
                      dropdownMatchSelectWidth: false,
                    }}
                  />
                );
              }
              return null;
            }}
          </ProFormDependency>

          <ProFormText rules={[{required: checkMode}]} label={'作业位置场所'} name="place"/>
          <ProFormSelect
            rules={[{required: checkMode}]}
            label={'风险源类型'}
            name="sourceType"
            valueEnum={sourceTypeData}
          />
          <ProFormTextArea rules={[{required: checkMode}]} label={'风险源'} name="source"/>
          {/*<ProFormCheckbox.Group*/}
          {/*  name="possibleResult" rules={[{required: true}]}*/}
          {/*  label="可能造成的后果"*/}
          {/*  options={['人员伤亡', '环境污染', '社会影响', '经济损失']}*/}
          {/*/>*/}
          {/*<ProFormCheckbox.Group*/}
          {/*  name="riskType" rules={[{required: true}]}*/}
          {/*  label="风险类型"*/}
          {/*  options={['物体打击', '车辆伤害', '机械伤害', '起重伤害', '触电', '淹溺',*/}
          {/*    '灼烫', '火灾', '高处坠落', '坍塌', '冒顶片帮', '透水', '放炮', '火药爆炸',*/}
          {/*    '瓦斯爆炸', '锅炉爆炸', '容器爆炸', '其他爆炸', '中毒和窒息', '其他伤害']}*/}
          {/*/>*/}

          <ProFormSelect
            rules={[{required: checkMode}]}
            label={'可能造成的后果'}
            name="possibleResult"
            mode={'multiple'}
            valueEnum={possibleResultData}
          />
          <ProFormSelect
            rules={[{required: checkMode}]}
            label={'风险类型'}
            name="riskType"
            mode={'multiple'}
            valueEnum={riskTypeData}
          />
          <ProFormSelect
            rules={[{required: checkMode}]}
            label={'风险等级'}
            name="riskLevel"
            fieldProps={{
              optionLabelProp: 'children',
              optionItemRender(item) {
                return <span style={{color: riskColor[item.value]}}>{item.label}</span>;
              },
            }}
            valueEnum={riskLevelData}
          />
          <ProFormTextArea rules={[{required: checkMode}]} label={'现有管控措施'} name="measure"/>
          <ProFormSelect
            rules={[{required: checkMode}]}
            label={'管控级别'}
            name="hierarchy"
            fieldProps={{
              optionLabelProp: 'children',
              optionItemRender(item) {
                return <span style={{color: hierarchyColor[item.value]}}>{item.label}</span>;
              },
            }}
            valueEnum={hierarchyData}
          />

          <ProFormSelect
            rules={[{required: checkMode}]}
            label={'辨识频率'}
            name="frequency"
            valueEnum={frequencyData}
          />
        </ModalForm>

        <Drawer
          width={800}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={false}
        >
          {currentRow?.place && (
            <ProDescriptions<RiskListItem>
              column={1}
              bordered={true}
              title={currentRow?.place}
              request={getRisk}
              layout={'horizontal'}
              params={currentRow}
              columns={columns as ProDescriptionsItemProps<RiskListItem>[]}
            />
          )}
        </Drawer>
      </PageContainer>
    </CheckModule>);
};

export default RiskCheckPage;
